package com.app.controller.miniProgram;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.app.service.*;
import com.app.model.*;
import com.app.util.*;
import com.app.vo.FormVo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tencentcloudapi.asr.v20190614.models.SentenceRecognitionRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@RestController
@Controller
@RequestMapping("/api/form")
public class FormController {
    @Autowired
    UserService userService;
    @Autowired
    FormService formService;
    @Autowired
    AttService attService;
    @Autowired
    FormUrlService formUrlService;
    @Autowired
    FormRemarkService formRemarkService;
    @Autowired
    ScoresService scoresService;

    @GetMapping("/getPageFormList")//分页查询
    public Result<Object> getPageFormList(
            @RequestParam("page") Integer page,
            @RequestParam("limit") Integer limit,
            @RequestParam(required = false) Integer userId,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Integer type,
            @RequestParam(required = false) Integer departmentId,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String uid = TokenUtils.verify(token);
        if (uid.equals("false")) {
            return Result.error(405, "token已过期");
        }
        UserModel userModel = userService.getUserById(Integer.parseInt(uid));
        if (userModel == null) {
            return Result.error(406, "用户不存在");
        }
        Page<FormModel> formModelPage = formService.getPageFormList(page, limit, userId, status);
        if (formModelPage == null) {
            return Result.error(200, "暂无数据");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        for (int i = 0; i < formModelPage.getRecords().size(); i++) {
            UserModel userModel1 = userService.getUserById(formModelPage.getRecords().get(i).getUserId());
            if (userModel1 != null) {
                formModelPage.getRecords().get(i).setUserName(userModel1.getUserName());
                formModelPage.getRecords().get(i).setFaceUrl(userModel1.getFaceUrl());
            }
            if (formModelPage.getRecords().get(i).getCrtTime() != null) {
                String crtTime = sdf.format(formModelPage.getRecords().get(i).getCrtTime());
                formModelPage.getRecords().get(i).setCrtTimeText(crtTime);
            }
            List<FormUrlModel> picList = formUrlService.getUrlByFormId(formModelPage.getRecords().get(i).getId(), 1);
            if (picList.size() != 0) {
                formModelPage.getRecords().get(i).setPicList(picList);
            }
            List<FormUrlModel> videoList = formUrlService.getUrlByFormId(formModelPage.getRecords().get(i).getId(), 2);
            if (videoList.size() != 0) {
                formModelPage.getRecords().get(i).setVideoList(videoList);
            }

        }
        int count = (int) formModelPage.getTotal();
        List<FormModel> formModelList;
        formModelList = formModelPage.getRecords();
        List<RoadModel> road = formService.get();

        for (int i = 0; i < formModelList.size(); i++) {
            for (int i1 = 0; i1 < road.size(); i1++) {
                if (formModelList.get(i).getStreet() != null && Objects.equals(formModelList.get(i).getStreet(), road.get(i1).getId())) {
                    formModelList.get(i).setStreetText(road.get(i1).getName());
                }
                if (formModelList.get(i).getRoad() != null && Objects.equals(formModelList.get(i).getRoad(), road.get(i1).getId())) {
                    formModelList.get(i).setRoadText(road.get(i1).getName());
                }
            }
        }
        FormVo vo = new FormVo();
        if (departmentId != null && departmentId != 0) {
            List<FormModel> collect = formModelList.stream().filter(FormModel -> FormModel.getDepId().equals(departmentId)).collect(Collectors.toList());
            Integer count1 = formService.selectCount(departmentId);
            vo.setCount(count1);
            vo.setList(collect);
            return Result.success(vo);
        }
        vo.setCount(count);
        vo.setList(formModelList);
        return Result.success(vo);
    }

    @PostMapping("/insertPlant")//    新增/修改表单管理
    public Result<Object> insertPlant(
            //@RequestParam("realName") String realName,
            @RequestParam("longitude") Double longitude,
            @RequestParam("latitude") Double latitude,
            @RequestParam("detAddress") String detAddress,//详细地址
            @RequestParam("address") String address,//详细地址
            @RequestParam("questionType") Integer questionType,//问题类型ID,category表
            @RequestParam("content") String content,//问题描述
            @RequestParam("pic") String pic,//图片
            @RequestParam(required = false) String video,//视频
            @RequestParam(required = false) Integer street,//街道
            @RequestParam(required = false) Integer road,//道路
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String uid = TokenUtils.verify(token);
        if (uid.equals("false")) {
            return Result.error(405, "token已过期");
        }
        UserModel userModel = userService.getUserById(Integer.parseInt(uid));
        if (userModel == null) {
            return Result.error(406, "用户不存在");
        }
        FormModel formModel = new FormModel();
        if (road != null && road != 0) {
            formModel.setRoad(road);
            formModel.setStreet(street);
            formModel.setSuperintend(1);
        }
        formModel.setUserId(userModel.getId());
        //formModel.setRealName(realName);
        formModel.setMobile(userModel.getMobile());
        formModel.setLongitude(longitude);
        formModel.setLatitude(latitude);
        formModel.setDetAddress(detAddress);
        formModel.setAddress(address);
        formModel.setQuestionType(questionType);
        formModel.setContent(content);
        formModel.setStatus(0);
//        formModel.setStatusTime(CommonHelp.getNowTimestamp());
        //UserModel userModel1 = new UserModel();
        //userModel1.setId(userModel.getId());
        //userModel1.setRealName(realName);
        //userService.update(userModel1);//更新用户真实姓名
        formModel.setCrtTime(CommonHelp.getNowTimestamp());
        formService.insert(formModel);
        FormUrlModel formUrlModel = new FormUrlModel();
        formUrlModel.setUrl(pic);
        formUrlModel.setType(1);
        formUrlModel.setFormId(formModel.getId());
        formUrlModel.setCrtTime(CommonHelp.getNowTimestamp());
        formUrlService.insert(formUrlModel);
        if (StringTool.isNotEmpty(video)) {
            FormUrlModel formUrlModel1 = new FormUrlModel();
            formUrlModel1.setUrl(video);
            formUrlModel1.setType(2);
            formUrlModel1.setFormId(formModel.getId());
            formUrlModel1.setCrtTime(CommonHelp.getNowTimestamp());
            formUrlService.insert(formUrlModel1);
        }
        List<ScoresModel> scoresModels = scoresService.getScoresListByUserId(userModel.getId());
        int score = 0;
        if (scoresModels != null && scoresModels.size() > 0) {
            for (int i = 0; i < scoresModels.size(); i++) {
                score += scoresModels.get(i).getScore();
            }
        }
        score += 1;
        ScoresModel scoresModel = new ScoresModel();
        scoresModel.setUserId(userModel.getId());
        scoresModel.setScore(1);
        scoresModel.setOperateType(1);
        scoresModel.setAfterScore(score);
        scoresModel.setCrtTime(CommonHelp.getNowTimestamp());
        scoresService.insert(scoresModel);
        return Result.success("操作成功");
    }

    @GetMapping("/getFormById")//详情
    public Result<Object> updateStatus(
            @RequestParam("id") Integer id,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String uid = TokenUtils.verify(token);
        if (uid.equals("false")) {
            return Result.error(405, "token已过期");
        }
        UserModel userModel = userService.getUserById(Integer.parseInt(uid));
        if (userModel == null) {
            return Result.error(406, "用户不存在");
        }
        FormModel formModel = formService.getFormById(id);
        UserModel userModel1 = userService.getUserById(formModel.getUserId());
        if (userModel1 != null) {
            formModel.setUserName(userModel1.getUserName());
            formModel.setFaceUrl(userModel1.getFaceUrl());
        }

        List<FormUrlModel> attModel = formUrlService.getUrlByFormId(formModel.getId(), 1);//查图片
        formModel.setPicList(attModel);
        List<FormUrlModel> attModel1 = formUrlService.getUrlByFormId(formModel.getId(), 2);//查视频
        if (attModel1.size() != 0) {
            formModel.setVideoList(attModel1);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        if (formModel.getCrtTime() != null) {
            String crtTime = sdf.format(formModel.getCrtTime());
            formModel.setCrtTimeText(crtTime);
        }
        FormRemarkModel remarkModel = formRemarkService.getRemarkByFormId(formModel.getId());
        if (remarkModel != null) {
            formModel.setFormRemarkModel(remarkModel);
        }
        //问题类型
        List<CategoryModel> categoryModels = formService.selectTypeList();
        for (int i = 0; i < categoryModels.size(); i++) {
            if (Objects.equals(categoryModels.get(i).getId(), formModel.getQuestionType())) {
                formModel.setQuestionTypeText(categoryModels.get(i).getName());
            }
        }
        List<RoadModel> road = formService.get();
        for (int i = 0; i < road.size(); i++) {
            if (Objects.equals(formModel.getRoad(), road.get(i).getId())) {
                formModel.setRoadText(road.get(i).getName());
            }
            if (Objects.equals(formModel.getStreet(), road.get(i).getId())) {
                formModel.setStreetText(road.get(i).getName());
            }
        }
        if (formModel == null) {
            return Result.error(500, "该条数据不存在");
        } else {
            return Result.success(formModel);

        }
    }

    @GetMapping("/deleteById")//删除
    public Result<Object> deleteById(
            @RequestParam("id") Integer id,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String uid = TokenUtils.verify(token);
        if (uid.equals("false")) {
            return Result.error(405, "token已过期");
        }
        UserModel userModel = userService.getUserById(Integer.parseInt(uid));
        if (userModel == null) {
            return Result.error(406, "用户不存在");
        }
        FormModel formModel = formService.getFormById(id);
        if (formModel == null) {
            return Result.error(500, "该条数据不存在");
        } else {
            formService.delete(id);
            return Result.success(null);
        }
    }

    //语音模糊匹配岗位
    @PostMapping("/voiceMatching")
    public Result<Object> voiceMatching(@RequestParam("file") MultipartFile file) throws IOException {
        String fileBase64 = Base64Utils.convertToBase64(file);
        String voice;
        SentenceRecognitionRequest req = new SentenceRecognitionRequest();
        req.setUsrAudioKey("voice");//短语音名称（随便填）
        req.setSubServiceType(2L);//2：一句话识别
        req.setProjectId(0L);
        req.setEngSerViceType("16k_zh-PY");
        req.setVoiceFormat("aac");
        req.setData(fileBase64);
        req.setSourceType(1L);
        req.setFilterPunc(1L);
        String msg = LiveUtils.SentenceRecognition(req);
        System.out.println(msg);
        JSONObject jsonObject = JSON.parseObject(msg);
        voice = jsonObject.getString("Result");
        return Result.success(voice);
    }

    //道路街道查询
    @GetMapping("/road")
    public Result<Object> road() {
        return Result.success(formService.road());
    }

}
